<?php

namespace Home\Model;

use Think\Model;

class UserModel extends Model {

    public function getUserList(){

    }

    //向用户推送数据, 返回更新条数
    public function pushArticleByCatid($userid, $catid){
        //判断用户是否有该分类
        $map_cron['userid'] = $userid;
        $map_cron['catid'] = $catid;
        $cron_detail = M('UserArticleCategoryCron')->where($map_cron)->find();
        $first_time = false;    //默认不是第一次推送
        if(empty($cron_detail)){
            //添加分类推送任务
            $first_time = true;
            M('UserArticleCategoryCron')->add($map_cron);
        }elseif($cron_detail['updatetime'] > NOW_TIME - 60*30){
            return 0;
        }

        //向用户推送某分类下的文章
        //文章必须是规定时间内的。
        $map['catid'] = $catid;
        $map['status'] = 99;
        //如果是第一次推送，则推送三个月内的。否则，推送计划后的
        if($first_time){
            $pagesize = 30;
        }else{
            $map['inputtime'] = array('gt', $cron_detail['updatetime']);
            $pagesize = 60;
        }
        // $map['inputtime'] = array('gt', NOW_TIME-3600);
        $artile_list = M('Article')->where($map)->field('id,`status`,catid,inputtime')->order('id DESC')->limit($pagesize)->select();
        if(empty($artile_list))
            return 0;
        foreach ($artile_list as $key => $value) {
            $arr_article_id[] = $value['id'];
        }
        //查看是否已经推送过
        $exist_list = M('UserArticle')->where(array('userid' => $userid, 'articleid' => array('in', $arr_article_id)))->index('articleid')->select();

        $count = 0;
        foreach ($artile_list as $key => $article) {
            if(!empty($exist_list) && array_key_exists($article['id'], $exist_list))
                continue;
            
            //循环推送
            $insert_info = [];
            $insert_info['userid'] = $userid;
            $insert_info['articleid'] = $article['id'];
            $insert_info['catid'] = $catid;
            M('UserArticle')->add($insert_info);
            $count++;
        }
        //更新推送时间
        M('UserArticleCategoryCron')->where($map_cron)->save(array('updatetime' => NOW_TIME));
        if($count == 0)
            return 0;

        //更新该分类count数量
        M('UserArticleCategory')->where($map_cron)->save(array('count' => array('exp', 'count+'.$count)));
        //更新folder数量
        $folder_list = M('UserArticleCategory')->where($map_cron)->select();
        foreach ($folder_list as $key => $value) {
            M('UserArticleFolder')->where(array('folder_id' => $value['folder_id']))->save(array('count' => array('exp', 'count+'.$count)));
        }

        return $count;
    }

    //向所有用户推送文章
    public function pushArticleById($id){
        //获取文章信息
        $map['status'] = 99;
        $map['id'] = $id;
        $detail = M('Article')->where($map)->field('id,catid,`status`')->find();
        if(empty($detail))
            return false;
        //查出有收藏该文章分类的所有用户
        $user_list = M('UserArticleCategory')->where(['catid' => $detail['catid']])->group('userid')->select();
        if(empty($user_list))
            return false;
        //保存文章信息
        foreach ($user_list as $key => $value) {
            $info = [];
            $info['userid'] = $value['userid'];
            $info['articleid'] = $id;
            $info['catid'] = $detail['catid'];
            $info['inputtime'] = getMicrotime();
            M('UserArticle')->add($info);
        }
        return true;
    }

	public function createGroup($userid, $gname = '我的好友'){
        $insert['userid']   = $userid ? $userid : session('userid');
        $insert['gname']    = $gname;
        $gid = M('user_friend_group')->add($insert);
        return $gid;
    }

    public function getFriendInfo($userid = null, $online_user_ids){
    	if(!$userid)
    		$userid = session('userid');

    	$online_user_list = $online_user_ids ? explode(',', $online_user_ids) : array();


    	$group_list_res = M('user_friend_group')->where(array('userid' => $userid))->order('gid')->select();
    	//初始化分组
    	foreach ($group_list_res as $group) {
    		$group_detail['groupname'] 	= $group['gname'];
    		$group_detail['id']			= $group['gid'];
    		$group_detail['list']		= array();
    		$group_list[$group['gid']] = $group_detail;
    	}
    	//取出用户的所有好友
    	$friend_list = M('user_friend')
                ->join('LEFT JOIN db_user ON db_user.userid=db_user_friend.friendid')
                ->order('db_user.status DESC')
                ->where(array('db_user_friend.userid' => $userid))
                ->field('db_user_friend.friendid, db_user_friend.groupid')->select();

		$userids= '';
    	if($friend_list){
    		foreach ($friend_list as $friend) {
    			$userids .= $userids ? ','.$friend['friendid'] : $friend['friendid'];
    		}
    	}
    	if(!empty($online_user_list)){
    		foreach ($online_user_list as $value) {
    			$userids .= $userids ? ','.$value : $value;
    		}
    	}
		//获取这些好友的基础信息
		$user_list = M('user')->where(array('userid' => array('in', $userids)))->field('userid AS id, nickname AS username, description AS sign, avatar')->index('id')->select();
    	if($friend_list){
	    	if($friend_list){
	    		foreach ($friend_list as $friend) {
                    if(!$user_list[$friend['friendid']])
                        continue;
	    			//存入$friend_list里的List数组
	    			$user_list[$friend['friendid']]['status'] = 'offline';	//默认为离线
	    			//是否在线
	    			if(!empty($online_user_list)){
	    				if(in_array($friend['friendid'], $online_user_list)){
	    					//设置该用户在线
	    					$user_list[$friend['friendid']]['status'] = 'online';
	    					//unset该在线用户
	    					unset($online_user_list[array_search($friend['friendid'], $online_user_list)]);
	    				}
	    			}
	    			$group_list[$friend['groupid']]['list'][] = $user_list[$friend['friendid']];
	    		}
	    	}
    	}
    	//机器人
        $online_friend_list[] = array(
            "username"  => "晴儿"
            ,"id"       =>  "1"
            ,"status"   =>  "online"
            ,"avatar"   =>  "http://tp1.sinaimg.cn/1571889140/180/40030060651/1"
            ,"sign"     =>  "没人在线？我陪你聊"
        );
        //取出在线好友列表
        if($online_user_list && !empty($online_user_list)){
            foreach($online_user_list as $v){
                //去掉自己 去掉不存在的
                if($v == $userid || !$user_list[$v])
                    continue;
                $online_friend_detail['username']   = $user_list[$v]['username'];
                $online_friend_detail['id']         = $user_list[$v]['id'];
                $online_friend_detail['sign']       = $user_list[$v]['sign'];
                $online_friend_detail['status']     = 'online';
                $online_friend_detail['avatar']     = $user_list[$v]['avatar'] ? $user_list[$v]['avatar'] : 'http://tp1.sinaimg.cn/1571889140/180/40030060651/1';
                $online_friend_list[] = $online_friend_detail;
            }
        }
    	//在线好友
        $online_friend = array(
            'groupname' => '在线网友',
            'id'        => 2,
            'list'      => $online_friend_list
        );
        $group_list = array_values($group_list);
        $group_list[] = $online_friend;
    	return $group_list;
    }

    public function getConfig($json = true){
        //获取文字高亮
        $config['highlighters'] = D('UserArticleHighlighter')->getUserHighlighterList();
        if($json == true){
            foreach ($config as $key => $value) {
                $config[$key] = json_encode($value);
            }
        }
        return $config;
    }
}

?>